<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\admin\model\Equipment;
use fast\Http;
use think\Validate;

class Bankuai extends Frontend
{

    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $layout = '';

	public function _initialize()
    {
        parent::_initialize();
	}
	
    public function index()
    {
		$bk_id = $this->request->param('bk_id', '', 'intval');
		
		$bankuai = \app\admin\model\Bankuai::get($bk_id);
		$shebei = Equipment::Field('id, device_name,device_serial')->whereIn('id', $bankuai->shebei)->paginate(10, null);
		
		$this->view->engine->layout('layout/default');
		$this->view->assign('config', array_merge($this->view->config, ['jsname' => '']));
		$this->view->assign('shebei', $shebei);
		$this->view->assign('bankuai', $bankuai);
		$this->view->assign('bk_id', $bk_id);
        return $this->view->fetch();
    }

	public function play()
	{
		$id = $this->request->param('id', '', 'intval');
		$shebei = Equipment::Field('id, device_name,device_serial,bk_id')->where('id', $id)->find();
		
		$shebeis = Equipment::Field('id, device_name,device_serial')->where('bk_id', $shebei['bk_id'])->select();
		
		$bankuai = \app\admin\model\Bankuai::get($shebei['bk_id']);
		
		$accessToken = getAccessToken();
		$this->view->assign('config', array_merge($this->view->config, ['jsname' => '']));
		$this->view->assign('accessToken', $accessToken);
		$this->view->assign('shebei', $shebei);
		$this->view->assign('shebeis', $shebeis);
		$this->view->assign('bankuai', $bankuai);
		return $this->view->fetch();
	}
	
	public function videolist()
	{
		$id = $this->request->param('id', '', 'intval');
		$shebei = Equipment::Field('id, device_name,device_serial,bk_id')->where('id', $id)->find();
		
		$accessToken = getAccessToken();
		Http::post('https://open.ys7.com/api/open/cloud/v1/project/'.$shebei['device_serial'], array('accessToken'=>$accessToken, 'projectId'=>$shebei['device_serial'], 'projectName'=>$shebei['device_name']));

		$map = array('accessToken'=>$accessToken, 'deviceSerial'=>$shebei['device_serial'], 'recType'=>1);
		$dateline = $this->request->param('dateline', '', 'trim');
		if($dateline)
		{
			$map['startTime'] = strtotime($dateline.' 00:00:00')*1000;
			$map['endTime'] = strtotime($dateline.' 23:59:59')*1000;
		}
		$result = Http::post('https://open.ys7.com/api/lapp/video/by/time', $map);
		$result = json_decode($result, true);
		if($result['code'] == 200)
		{
			$fileList = $result['data'];
		}
		else
		{
			$this->error($result['msg']);
		}
		
		//$result = Http::get('https://open.ys7.com/api/open/cloud/v1/files?accessToken='.$accessToken.'&projectId='.$shebei['device_serial']);
		//$result = json_decode($result, true);
		// if($result['meta']['code'] == 200)
		// {
			// $fileList = $result['data'];
		// }
		// else
		// {
			// $this->error($result['meta']['message']);
		// }

		$this->view->engine->layout('layout/default');
		$this->view->assign('fileList', $fileList);
		$this->view->assign('shebei', $shebei);
		return $this->view->fetch();
	}
	
	public function luzhi()
	{
		$id = $this->request->param('id', '', 'intval');
		$shebei = Equipment::Field('id, device_name,device_serial')->where('id', $id)->find();
		
		if ($this->request->isPost()) {
			$starttime = $this->request->post("starttime");
			$endtime = $this->request->post("endtime");
			//$token = $this->request->post('__token__');
			
			$starttime = str_replace(['-', ' ', ':'], '', $starttime);
			$endtime = str_replace(['-', ' ', ':'], '', $endtime);

			/* $rule = [
                'starttime'   => 'require',
                'endtime'   => 'require',
                '__token__'     => 'token',
            ];
			
			$data = [
                'starttime'   => $starttime,
                'endtime'   => $endtime,
                '__token__'     => $token,
            ];
			
			$validate = new Validate($rule);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            } */
			
            $accessToken = getAccessToken();
			$url = 'https://open.ys7.com/api/open/cloud/v1/rec/video/save';
			$header = array('Content-type:application/x-www-form-urlencoded', 'accessToken:'.$accessToken, 'deviceSerial:'.$shebei['device_serial']);
			$data = array('projectId'=>$shebei['device_serial'], 'recType'=>'cloud', 'startTime'=>$starttime, 'endTime'=>$endtime);
			$result = $this->posturl($url, $data, $header);
			if($result['meta']['code'] == 200)
			{
				$this->success('录制成功', url('bankuai/videolist', ['id'=>$shebei['id']]));
			}
			else
			{
				 $this->error($result['meta']['message']);
			}
		}
		
		$this->view->engine->layout('layout/default');
		$this->view->assign('shebei', $shebei);
		return $this->view->fetch();
	}
	
	public function download()
	{
		$fileId = $this->request->param('fileId', '', 'trim');
		$id = $this->request->param('id', '', 'intval');
		$shebei = Equipment::Field('id, device_name,device_serial')->where('id', $id)->find();
		
		$accessToken = getAccessToken();
		$result = Http::get('https://open.ys7.com/api/open/cloud/v1/file/download?accessToken='.$accessToken.'&fileId='.$fileId.'&projectId='.$shebei['device_serial']);
		$result = json_decode($result, true);
		if($result['meta']['code'] == 200)
		{
			$urls = $result['data']['urls'][0];

			//header("Content-type:application/octet-stream");
			header('Content-type: video/mp4');
			header("Accept-Ranges:bytes");
			header("Content-Disposition:attachment;filename=".$shebei['device_name'].".mp4");
			
			echo file_get_contents($urls);
			exit;
		}
		else
		{
			$this->error($result['meta']['message']);
		}
	}
	
	public function transcribe()
	{
		$id = $this->request->param('id', '', 'intval');
		$startTime = $this->request->param('startTime', '', 'trim');
		$endTime = $this->request->param('endTime', '', 'trim');
		$shebei = Equipment::Field('id, device_name,device_serial')->where('id', $id)->find();
		
		$backdata = array('code'=>0);
		
		$map = array('starttime'=>$startTime, 'endtime'=>$endTime, 'deviceserial'=>$shebei['device_serial'], 'projectid'=>$shebei['device_serial']);
		$task = db('transcribe')->where($map)->find();
		if($task)
		{
			$taskid = $task['taskid'];
			
			$backdata['code'] = 1;
			$backdata['taskid'] = $taskid;
		}
		else
		{
			$accessToken = getAccessToken();
			$url = 'https://open.ys7.com/api/open/cloud/v1/rec/video/save';
			$header = array('Content-type:application/x-www-form-urlencoded', 'accessToken:'.$accessToken, 'deviceSerial:'.$shebei['device_serial']);
			$data = array('projectId'=>$shebei['device_serial'], 'recType'=>'cloud', 'startTime'=>date('YmdHis', $startTime/1000), 'endTime'=>date('YmdHis', $endTime/1000));
			$result = $this->posturl($url, $data, $header);
			if($result['meta']['code'] == 200)
			{
				$taskId = $result['data']['taskId'];
				
				$map['taskid'] = $taskId;
				$map['rectype'] = 'cloud';
				db('transcribe')->insert($map);
				
				$backdata['code'] = 2;
				$backdata['taskid'] = $taskId;
			}
			else
			{
				 $backdata['msg'] = $result['meta']['message'];
			}
		}
		
		echo json_encode($backdata);
		exit;
	}
	
	public function filelist()
	{
		$id = $this->request->param('id', '', 'intval');
		$taskId = $this->request->param('taskid', '', 'trim');
		$shebei = Equipment::Field('id, device_name,device_serial')->where('id', $id)->find();
		
		$accessToken = getAccessToken();
		$result = Http::get('https://open.ys7.com/api/v3/open/cloud/task/files?accessToken='.$accessToken.'&taskId='.$taskId.'&hasUrl=true');
		$result = json_decode($result, true);
		if($result['meta']['code'] == 200)
		{
			$fileList = $result['data'];
			
			$this->view->assign('fileList', $fileList);
		}
		else
		{
			 $this->error($result['meta']['message']);
		}
		
		$this->view->engine->layout('layout/default');
		$this->view->assign('shebei', $shebei);
		return $this->view->fetch();
	}
	
	public function filelink()
	{
		$fileId = $this->request->param('fileId', '', 'trim');
		$id = $this->request->param('id', '', 'intval');
		$startTime = $this->request->param('startTime', '', 'trim');
		$endTime = $this->request->param('endTime', '', 'trim');
		$shebei = Equipment::Field('id, device_name,device_serial')->where('id', $id)->find();
		
		$starttime = date('YmdHis', $startTime/1000);
		$endtime = date('YmdHis', $endTime/1000);
		
		$accessToken = getAccessToken();
		$url = 'https://open.ys7.com/api/open/cloud/v1/rec/video/save';
		$header = array('Content-type:application/x-www-form-urlencoded', 'accessToken:'.$accessToken, 'deviceSerial:'.$shebei['device_serial']);
		$data = array('projectId'=>$shebei['device_serial'], 'recType'=>'cloud', 'startTime'=>$starttime, 'endTime'=>$endtime);
		$result = $this->posturl($url, $data, $header);
		if($result['meta']['code'] == 200)
		{
			$taskId = $result['data']['taskId'];
			$result = Http::get('https://open.ys7.com/api/v3/open/cloud/task/files?accessToken='.$accessToken.'&taskId='.$taskId.'&hasUrl=true');
			$result = json_decode($result, true);
			var_dump($result);exit;
		}
		else
		{
			 $this->error($result['meta']['message']);
		}
		
			
		$result = Http::get('https://open.ys7.com/api/open/cloud/v1/file/download?accessToken='.$accessToken.'&fileId='.$fileId.'&projectId='.$shebei['device_serial']);
		$result = json_decode($result, true);
		if($result['meta']['code'] == 200)
		{
			$urls = $result['data']['urls'][0];

			//header("Content-type:application/octet-stream");
			header('Content-type: video/mp4');
			header("Accept-Ranges:bytes");
			header("Content-Disposition:attachment;filename=".$shebei['device_name'].".mp4");
			
			echo file_get_contents($urls);
			exit;
		}
		else
		{
			$this->error($result['meta']['message']);
		}
	}
	
	protected function posturl($url,$data, $header="Content-type:application/json")
	{
		$data = http_build_query($data);
		$ch = curl_init(); //初始化CURL句柄 
		curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
		curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output,true);
	}

}
